package com.cxl.price.service;

import java.util.Iterator;
import java.util.Set;

import javax.annotation.Resource;

import org.htmlparser.util.ParserException;
import org.springframework.stereotype.Service;

import com.cxl.parser.grab.GrabCommon;
import com.cxl.price.bean.Good;
import com.cxl.price.bean.Goods;
import com.cxl.price.bean.Shop;
import com.cxl.price.dao.GoodDao;
import com.summer.core.service.impl.BaseServiceImpl;

/**
 * @about: 商城商品 service 实现
 * @author: wwwlike
 * @create: 2011-06-14
 */
@Service
public class GoodServiceImpl extends BaseServiceImpl<Good, String, GoodDao>
		implements GoodService {

	@Resource
	public void setDao(GoodDao dao) {
		this.dao = dao;
	}
	
	
	//更新URL和价格为商店里指定最低的
	public Double getMinPrice(Goods goods)
	{
		Set goodSet=goods.getGood();
		if(goods==null||goodSet.size()==0)
			return null;
		Iterator<Good> iter=goodSet.iterator();
		Good  goodtemp=null;
		
		
		while(iter.hasNext())
		{
			Good good=iter.next();
			if(good.isIs_master()==true)
			{
				good.setIs_master(false);
				dao.update(good);
				
			}
		
				if( goodtemp==null||goodtemp.getPrice()>good.getPrice())
				{
					goodtemp=good;
				}
				
		}
		//更新master
		if(goodtemp.getId()!=null)
		{
			goodtemp.setIs_master(true);
			dao.update(goodtemp);
			return goodtemp.getPrice();
		}
		return null;
	}
	
	public void updatePrice(Good good) throws InstantiationException, IllegalAccessException, ClassNotFoundException, ParserException
	{
		
		GrabCommon grab=(GrabCommon) Class.forName(good.getShop().getGrabClassPath()).newInstance();
		grab.setUrl(good.getUrl());
		Double newPrice=grab.getPrice();
		if(newPrice!=good.getPrice())
		{
			good.setPrice(newPrice);
			dao.update(good);
		}
	}
}
